
import Utils from './Utils'

var AssetsManager = function () {
  this._cachedAssets = {}
}

var Asset = function (name) {
  this._name = name
  this._currentState = '/static/assets/' + this._name + '_normal.png'
  this._assetHolders = []
}

Asset.prototype.currentState = function () {
  return this._currentState
}

Asset.prototype.normal = function () {
  this._currentState = '/static/assets/' + this._name + '_normal.png'
  this.notifyStateChanged()
}

Asset.prototype.focused = function () {
  this._currentState = '/static/assets/' + this._name + '_focused.png'
  this.notifyStateChanged()
}

Asset.prototype.disabled = function () {
  this._currentState = '/static/assets/' + this._name + '_disabled.png'
  this.notifyStateChanged()
}

Asset.prototype.check = function (assetHolder) {
  var i = this._assetHolders.length
  var pos = -1
  while (i--) {
    if (this._assetHolders[i] === assetHolder) {
      pos = i
    }
  }
  return pos
}

Asset.prototype.registerCallback = function (assetHolder) {
  if (assetHolder && Utils.isFunction(assetHolder.onAssetStateChanged)) {
    if (this.check(assetHolder) < 0) {
      this._assetHolders.push(assetHolder)
    }
  }
}

Asset.prototype.unregisterCallback = function (assetHolder) {
  var pos = this.check(assetHolder)
  if (pos > -1) {
    this._assetHolders.splice(pos, 1)
  }
}

Asset.prototype.notifyStateChanged = function () {
  var i = this._assetHolders.length
  while (i--) {
    var holder = this._assetHolders[i]
    holder.onAssetStateChanged(this, this.currentState())
  }
}

AssetsManager.Asset = Asset

AssetsManager.prototype.getAsset = function (assetName) {
  return new Asset(assetName)
}

AssetsManager.install = function (Vue, options) {
  Vue.prototype.$assetsManager = new AssetsManager()
}

export { Asset }
export default AssetsManager
